layui.use(['layer', 'table', 'form', 'admin', 'ax', 'func', 'laydate', 'formSelects'], function () {
    //var $ = layui.jquery;
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var form = layui.form;
    var formSelects = layui.formSelects;
    var layer = layui.layer;
    //年月选择器
    laydate.render({
        elem: '#dateStr'
        , type: 'month'
    });

    /**
     * 管理
     */
    var DsstoreBillDelivery = {
        tableId: "dsstoreBillDeliveryTable"
    };

    /**
     * 检索店名
     */
    var languageAjax = new $ax(Feng.ctxPath + "/btyShop/selectAll");
    var languageResult = languageAjax.start();
    console.info(languageResult);
    $.each(languageResult, function (index, val) {
        $("#otherSideCode").append("<option value='" + val.shopCode + "'>" + val.shopName + "</option>");
    });
    form.render('select');


    /**
     * 检索品类
     */
    // var itemSmallClassCodeAjax = new $ax(Feng.ctxPath + "/itemType/itemlist");
    // var itemSmallClassCodeAjaxeResult = itemSmallClassCodeAjax.start();
    // console.info(itemSmallClassCodeAjaxeResult);
    // $.each(itemSmallClassCodeAjaxeResult, function (index, val) {
    //     $("#itemSmallClassCode").append("<option value='" + val.itemTypeCode + "'>" + val.itemTypeName + "</option>");
    // });
    // form.render('select');


    /**
     * 检索品项
     */
    // var itemCodeAjax = new $ax(Feng.ctxPath + "/itemInterface/itemlist");
    // var itemCodeAjaxeResult = itemCodeAjax.start();
    // console.info(itemCodeAjaxeResult);
    // $.each(itemCodeAjaxeResult, function (index, val) {
    //     $("#itemCode").append("<option value='" + val.itemCode + "'>" + val.itemName + "</option>");
    // });
    // form.render('select');
    //
    // //选择品类时，品项显示为该品类下的
    // form.on('select(itemSmallClassCode)', function (data) {
    //     $("#itemCode").html("");
    //     $("#itemCode").append("<option value=''>" + "全部品项" + "</option>");
    //     var itemlistAjax = new $ax(Feng.ctxPath + "/itemInterface/itemlist");
    //     itemlistAjax.set("itemTypeCode", $("#itemSmallClassCode").find("option:selected").val());
    //     var itemlistResult = itemlistAjax.start();
    //     console.info(itemlistResult);
    //     $.each(itemlistResult, function (index, val) {
    //         $("#itemCode").append("<option value='" + val.itemCode + "'>" + val.itemName + "</option>");
    //     });
    //     form.render('select');
    // });


    /**
     * 初始化表格的列
     */
    DsstoreBillDelivery.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {title: '序号',templet: '#indexTpl', width:60},
            {field: 'id', sort: true, title: '视图数据id', hide: 'true'},
            //{field: 'billNo', sort: true, title: '单据系统单号'},
            {field: 'shopName', sort: false, title: '配送中心', minWidth: 130},
            {field: 'shopCode', sort: false, title: '配送中心Code', hide: 'true'},
            {field: 'otherSideName', sort: false, title: '门店', minWidth: 210},
            {field: 'otherSideCode', sort: false, title: '门店编号', hide: 'true'},
            {field: 'billBusType', sort: false, title: '业务类型', minWidth: 130},
            {field: 'billBusTypeId', sort: false, title: '', hide: 'true'},
            {field: 'itemSmallClassName', sort: false, title: '品类',width:60},
            {field: 'itemSmallClassCode', sort: false, title: '', hide: 'true'},
            {field: 'itemCode', sort: false, title: '品项编号'},
            {field: 'itemName', sort: false, title: '品项'},
            {field: 'itemSpec', sort: false, title: '品项规格'},
            // {field: 'mainUnit', sort: true, title: '主单位'},
            // {field: 'inMainAmount', sort: true, title: '主入库数量'},
            // {field: 'outMainAmount', sort: true, title: '主出库数量'},
            {field: 'itemUnitName', sort: false, title: '单位',width:60},
            {field: 'inMainAmount', sort: false, title: '业务入库数量', hide: 'true'},
            {field: 'outMainAmount', sort: false, title: '业务出库数量', hide: 'true'},
            {field: 'amount', sort: false, title: '数量', totalRow: true, width:110},
            {field: 'unitPrice', sort: false, title: '含税配送单价'},
            {field: 'saleMoney', sort: false, title: '含税配送金额', totalRow: true, width:125},
            {field: 'itemBigClassName', sort: false, title: '', hide: 'true'},
            {field: 'itemAssistNo', sort: false, title: '品项辅助编号', hide: 'true'},
            //{field: 'sellTaxes', sort: true, title: ''},

            // {field: 'arriveMoney', sort: true, title: ''},
            // {field: 'storeCode', sort: true, title: ''},
            // {field: 'outputRate', sort: true, title: ''},
            // {field: 'storeBillRemark', sort: true, title: ''},
            // {field: 'outMainAmount', sort: true, title: ''},
            //  {field: 'itemSign', sort: true, title: ''},

            // {field: 'taxMoney', sort: true, title: ''},
            // {field: 'storeBillDtid', hide: true, title: ''},
            // {field: 'modifyDate', sort: true, title: '修改时间'},
            // {field: 'storeName', sort: true, title: ''},
            // {field: 'storeBillidRemark', sort: true, title: ''},

            // {field: 'giftFlag', sort: true, title: ''},
            // {field: 'outStoreMoney', sort: true, title: '出库金额'},
            // {field: 'itemId', sort: true, title: '品项ID'},
            // {field: 'storeBillReState', sort: true, title: ''},
            // {field: 'busUser', sort: true, title: ''},
            // {field: 'taxes', sort: true, title: ''},
            // {field: 'batchCode', sort: true, title: ''},
            // {field: 'inStoreMoney', sort: true, title: '入库金额'},
            // {field: 'isOut', sort: true, title: ''},
            // {field: 'shopId', sort: true, title: '门店ID'},
            // {field: 'makeTime', sort: true, title: '生产日期'},
            // {field: 'processMoney', sort: true, title: ''},
            // {field: 'pushOutStoreMoney', sort: true, title: ''},
            // {field: 'pushOutStoreAmount', sort: true, title: ''},
            // {field: 'storeBillId', sort: true, title: ''},
            // {field: 'sellIncludeTaxMoney', sort: true, title: ''},
            // {field: 'otherSideType', sort: true, title: ''},
            // {field: 'pushInStoreMoney', sort: true, title: ''},
            // {field: 'yield', sort: true, title: ''},
            // {field: 'arriveAmount', sort: true, title: ''},
            //  {field: 'sysBatchCode', sort: true, title: '系统批次号'},
            //  {field: 'createDate', sort: true, title: '创建时间'},
            //  {field: 'auditDate', sort: true, title: ''},
            //  {field: 'otherSideId', sort: true, title: ''},
            // {field: 'billType', sort: true, title: ''},
            // {field: 'sellTaxMoney', sort: true, title: ''},

            // {field: 'pushInStoreAmount', sort: true, title: ''},
            // {field: 'busDate', sort: true, title: ''},
             {field: 'aPYear', sort: false,hide:true, title: '会计年'},
            // {field: 'itemBigClassCode', sort: true, title: ''},

            // {field: 'storeId', sort: true, title: ''},
            // {field: 'itemAbc', sort: true, title: ''},
            // {field: 'arrivalDate', sort: true, title: ''},
             {field: 'aPMonth', sort: false,hide:true, title: '会计月'},

            // {field: 'includeTaxMoney', sort: true, title: ''},
            //{field: 'parentBillNo', sort: true, title: ''},
            {field: 'auId', sort: false, title: '审核记录id', hide: 'true'},
            {field: 'status', sort: false, title: '状态', templet: '#statusTpl'},
            {field: 'zfbkh', sort: false, title: '卡号', width:80},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    var queryData = {};
    DsstoreBillDelivery.search = function () {
        queryData['dateStr'] = $('#dateStr').val();
        //var itemCode=formSelects.value('itemCode', 'valStr');
        //queryData['itemCode'] =itemCode;
        queryData['itemCode'] = $('#itemCode').val();
        queryData['otherSideCode'] = $("#otherSideCode").find("option:selected").val();
        queryData['otherSideName'] = $('#otherSideName').val();
        //queryData['itemSmallClassCode'] = $("#itemSmallClassCode").find("option:selected").val();
        queryData['billBusTypeId'] = $('#billBusTypeId').val();
        queryData['status'] = $('#status').val();
        queryData['delFlag'] = $('#delFlag').val();
        // table.reload(DsstoreBillDelivery.tableId, {
        //     where: queryData, page: {curr: 1}
        // });
        DsstoreBillDelivery.tableCfg.where = queryData;
        table.render(DsstoreBillDelivery.tableCfg);
    };


    /**
     * 弹出添加对话框
     */
    DsstoreBillDelivery.openAddDlg = function () {
        func.open({
            title: '添加',
            content: Feng.ctxPath + '/dsstoreBillDelivery/add',
            tableId: DsstoreBillDelivery.tableId
        });
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    DsstoreBillDelivery.openEditDlg = function (data) {
        func.open({
            title: '修改',
            content: Feng.ctxPath + '/dsstoreBillDelivery/edit?storeBillDtid=' + data.storeBillDtid,
            tableId: DsstoreBillDelivery.tableId
        });
    };


    /**
     * 导出excel按钮
     */
    DsstoreBillDelivery.exportExcel = function () {
        var checkRows = table.checkStatus(DsstoreBillDelivery.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    DsstoreBillDelivery.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/dsstoreBillDelivery/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(DsstoreBillDelivery.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("storeBillDtid", data.storeBillDtid);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    DsstoreBillDelivery.tableCfg = {
        //toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        elem: '#' + DsstoreBillDelivery.tableId,
        url: Feng.ctxPath + '/dsstoreBillDelivery/list2',
        page: false,
        limit: 100000,
        height: "full-129",
        cellMinWidth: 100,
        where: {dateStr: $("#dateStr").val()},
        totalRow: true,
        cols: DsstoreBillDelivery.initColumn()
        ,done : function(res, curr, count){//数据渲染完的回调。
            var totalNum1=this.elem.next().find('.layui-table-total td[data-field="amount"] .layui-table-cell').text();//获取合计行的合计结果
            $('#totalNum').val(totalNum1);
            $('#selectedNum').val(0);
            $('#lastNum').val(totalNum1);

    }
    };


    // //头工具栏事件
    // table.on('toolbar(dsstoreBillDeliveryTable)', function (obj) {
    //     var checkStatus = table.checkStatus(obj.config.id);
    //     switch (obj.event) {
    //         case 'getCheckData':
    //             var data = checkStatus.data;
    //             layer.alert(JSON.stringify(data));
    //             break;
    //         case 'getCheckLength':
    //             var data = checkStatus.data;
    //             layer.msg('选中了：' + data.length + ' 个');
    //             break;
    //         case 'isAll':
    //             layer.msg(checkStatus.isAll ? '全选' : '未全选');
    //             break;
    //
    //         //自定义头工具栏右侧图标 - 提示
    //         case 'LAYTABLE_TIPS':
    //             layer.alert('这是工具栏右侧自定义的一个图标按钮');
    //             break;
    //     }
    //     ;
    // });

    //首次加载表格
    queryData['dateStr'] = $('#dateStr').val();
    queryData['itemCode'] = $('#itemCode').val();
    queryData['delFlag'] = $('#delFlag').val();
    DsstoreBillDelivery.tableCfg.where = queryData;
    table.render(DsstoreBillDelivery.tableCfg);


    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        DsstoreBillDelivery.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

        DsstoreBillDelivery.openAddDlg();

    });

    // 导出excel
    $('#btnExp').click(function () {
        DsstoreBillDelivery.exportExcel();
    });
    /**
     * 点击审核按钮
     * @param data
     */
    DsstoreBillDelivery.auditItem = function (data) {
        let index = layer.open({
            area: ['300px', '200px'],
            title: '审核',
            btn: ['通过', '取消'],
            btnAlign: 'c',
            type: 1,
            async: false,
            content: '<div style="padding: 20px 20px;">是否确认通过审核？</div>',
            yes: function (index, layero) {
                //提交审核结果 通过状态为 1：已通过
                data.status = 1;
                //二次审核的数据，将已经保存的同月数据，若有操作视为更新
                data.auId = data.auId;

                DsstoreBillDelivery.shenHe(data);
                //table.reload(BtyGoodsPay.tableId);
                layer.close(index);
            },
            btn2: function (index, layero,) {
                layer.close(index);
            },
        });

    };
    /**
     * 点击恢复按钮
     * @param data
     */
    DsstoreBillDelivery.recoverItem = function (data) {
        let index = layer.open({
            area: ['300px', '200px'],
            title: '审核',
            btn: ['通过', '取消'],
            btnAlign: 'c',
            type: 1,
            async: false,
            content: '<div style="padding: 20px 20px;">是否确认通过审核？</div>',
            yes: function (index, layero) {
                //提交审核结果 通过状态为 1：已通过
                data.status = 1;
                //二次审核的数据，将已经保存的同月数据，若有操作视为更新
                data.auId = data.auId;
                DsstoreBillDelivery.recover(data);
                //table.reload(BtyGoodsPay.tableId);
                layer.close(index);
            },
            btn2: function (index, layero,) {
                layer.close(index);
            },
        });

    };
    /**
     * 提交审核结果
     */
    DsstoreBillDelivery.shenHe = function (data) {


        $.ajax({
            type: "post",
            url: "/dsstoreBillDelivery/audit",
            data: data,
            async: false,
            success: function (rs) {
                if (rs.success) {
                    layer.msg('审核已通过！');
                } else {
                    Feng.error(rs.message);
                }
                // parent.location.reload();
                table.reload(DsstoreBillDelivery.tableId);
            }
        });
    };

    /**
     * 提交恢复请求
     */
    DsstoreBillDelivery.recover = function (data) {
        $.ajax({
            type: "post",
            url: "/dsstoreBillDelivery/recover",
            data: data,
            async: false,
            success: function (rs) {
                if (rs.success) {
                    layer.msg('数据已恢复！');
                } else {
                    Feng.error(rs.message);
                }
                // parent.location.reload();
                table.reload(DsstoreBillDelivery.tableId);
            }
        });
    };

    // 工具条点击事件
    table.on('tool(' + DsstoreBillDelivery.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            DsstoreBillDelivery.openEditDlg(data);
        } else if (layEvent === 'delete') {
            DsstoreBillDelivery.onDeleteItem(data);
        } else if (layEvent === 'audit') {
            DsstoreBillDelivery.auditItem(data);
        }else if (layEvent === 'recover') {
            DsstoreBillDelivery.recoverItem(data);
        }
    });


    /**
     * 批量审核
     */
    $('#batchAudit').click(function () {
        DsstoreBillDelivery.batchAudit();
    });


    DsstoreBillDelivery.batchAudit = function () {
        var checkRows = table.checkStatus(DsstoreBillDelivery.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要批量审核的数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/dsstoreBillDelivery/batchAudit", function (data) {
                    if (data.code == 201) {
                        Feng.success(data.message);
                    } else {
                        Feng.success("批量审核成功!");
                    }
                    table.reload(DsstoreBillDelivery.tableId);


                }, function (data) {
                    Feng.error("批量审核失败!" + data.responseJSON.message + "!");
                });
                ajax.set("ids", ids);
                ajax.start();
            };
            Feng.confirm("是否确认批量审核?", operation);
        }
    };


    /**
     * 批量审核
     */
    $('#batchDel').click(function () {
        DsstoreBillDelivery.batchDel();
    });
    DsstoreBillDelivery.batchDel = function () {
        var checkRows = table.checkStatus(DsstoreBillDelivery.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要批量删除的数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/dsstoreBillDelivery/batchDel", function (data) {
                    if (data.code == 201) {
                        Feng.success(data.message);
                    } else {
                        Feng.success("批量删除成功!");
                    }
                    table.reload(DsstoreBillDelivery.tableId);


                }, function (data) {
                    Feng.error("批量删除失败!" + data.responseJSON.message + "!");
                });
                ajax.set("ids", ids);
                ajax.start();
            };
            Feng.confirm("是否确认批量删除?", operation);
        }
    };


    /**
     * 批量审核
     */
    $('#batchRecover').click(function () {
        DsstoreBillDelivery.batchRecover();
    });
    DsstoreBillDelivery.batchRecover = function () {
        var checkRows = table.checkStatus(DsstoreBillDelivery.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要批量恢复的数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/dsstoreBillDelivery/batchRecover", function (data) {
                    if (data.code == 201) {
                        Feng.success(data.message);
                    } else {
                        Feng.success("批量恢复成功!");
                    }
                    table.reload(DsstoreBillDelivery.tableId);


                }, function (data) {
                    Feng.error("批量恢复失败!" + data.responseJSON.message + "!");
                });
                ajax.set("ids", ids);
                ajax.start();
            };
            Feng.confirm("是否确认批量恢复?", operation);
        }
    };

    // 导出excel
    $('#batchExport').click(function () {
        var dateStr = $('#dateStr').val();
        var itemCode = $('#itemCode').val();
        //var itemCode=formSelects.value('itemCode', 'valStr');
        var otherSideCode = $("#otherSideCode").find("option:selected").val();
        //var itemSmallClassCode= $("#itemSmallClassCode").find("option:selected").val();
        var billBusTypeId = $('#billBusTypeId').val();
        var status = $('#status').val();
        var delFlag = $('#delFlag').val();
        if (dateStr == "" || dateStr == undefined || dateStr == null) {
            Feng.error("请选择日期");
        } else {
            //获取导出Excel的数据
            var url = Feng.ctxPath + "/dsstoreBillDelivery/listExport?dateStr=" + dateStr
                + "&itemCode=" + itemCode
                + "&otherSideCode=" + otherSideCode
                + "&billBusTypeId=" + billBusTypeId
                + "&status=" + status
                + "&delFlag="+ delFlag;
            location.href = url;
        }
    });

    // formSelects.config('itemCode', {
    //     searchUrl: Feng.ctxPath + "/itemInterface/specifiedItemlist",
    //     keyName: 'itemName',
    //     keyVal: 'itemCode'
    // })

    // var itemCodeAjax = new $ax(Feng.ctxPath + "/itemInterface/specifiedItemlist");
    // var itemCodeResult = itemCodeAjax.start();
    // $.each(itemCodeResult, function( index, val ) {
    //     $("#itemCode").append("<option value='"+val.itemCode+"'>"+val.itemName+"</option>");
    // } );
    // form.render('select');
});


layui.use('table', function () {
    var table = layui.table;
    //监听表格复选框选择


    table.on('checkbox(dsstoreBillDeliveryTable)', function (obj) {
        //obj.data.amount
        // console.log(obj)
        // selectedNum=selectedNum+obj.data.amount;
        // $('#selectedNum').val(selectedNum);
        var selectedNum=0;
        var checkRows = table.checkStatus('dsstoreBillDeliveryTable');
        var data = checkRows.data;

        if (checkRows.data.length === 0) {
            $('#selectedNum').val(selectedNum);
        }else{
            for (var i in data){
                selectedNum=selectedNum+data[i].amount;
            }
            $('#selectedNum').val(selectedNum);
        }

        var total=$('#totalNum').val();

        var lastNum=total-selectedNum;
        $('#lastNum').val(lastNum);


    });
    var $ = layui.$, active = {
        getCheckData: function () { //获取选中数据
            var checkStatus = table.checkStatus('dsstoreBillDeliveryTable')
                , data = checkStatus.data;
            layer.alert(JSON.stringify(data));
        }
        , getCheckLength: function () { //获取选中数目
            var checkStatus = table.checkStatus('dsstoreBillDeliveryTable')
                , data = checkStatus.data;
            layer.msg('选中了：' + data.length + ' 个');
        }
        , isAll: function () { //验证是否全选
            var checkStatus = table.checkStatus('dsstoreBillDeliveryTable');
            layer.msg(checkStatus.isAll ? '全选' : '未全选')
        }
    };

    $('.demoTable .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});

